<template>
    <el-main>
        <el-form :model="searchParam" :inline="true">
            <el-form-item>
                <el-input v-model="searchParam.nickName" placeholder="请输入姓名" @input="onInput"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button :icon="Search" @click="searchBtn">搜索</el-button>
                <el-button icon="Close" type="danger" @click="resetBtn">重置</el-button>
                <el-button icon="Plus" type="primary" @click="addBtn">新增</el-button>
            </el-form-item>
        </el-form>
        <SysDialog :title="dialog.title" :visible="dialog.visible" @close="parentClose" @confirm="onConfirm">
            <template v-slot:content>
                <el-form ref="addRef" :model="addModel" label-width="auto" :rules="rules">
                    <el-form-item label="姓名" prop="nickName">
                        <el-input v-model="addModel.nickName" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="addModel.sex">
                            <el-radio value="0">男</el-radio>
                            <el-radio value="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="addModel.phone" />
                    </el-form-item>
                    <el-form-item label="登录账户" prop="username">
                        <el-input v-model="addModel.username" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addModel.password" />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="addModel.status">
                            <el-radio value="0">启用</el-radio>
                            <el-radio value="1">停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </template>
        </SysDialog>

        <!-- 管理员数据列表 -->
        <el-table :data="tableList" :height="tableHeight" border stripe>
            <el-table-column prop="nickName" label="姓名"></el-table-column>
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    <!-- <el-button @click="printScope(scope)">打印 Scope</el-button> -->
                    <el-tag v-if="scope.row.sex == '1'" type="danger" effect="dark">女</el-tag>
                    <el-tag v-if="scope.row.sex == '0'" effect="dark">男</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="username" label="账户"></el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == '1'" type="danger" effect="dark">停用</el-tag>
                    <el-tag v-if="scope.row.status == '0'" effect="dark">启用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="320" align="center">
                <template #default="scope">
                    <el-button type="primary" icon="Edit" size="default" @click="editBtn(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="Delete" size="default" @click="deleteBtn(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="searchParam.currentPage"
            :page-sizes="[10, 20, 40, 80, 100]" :page-size="searchParam.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="searchParam.total" background>
        </el-pagination>

    </el-main>
</template>

<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import SysDialog from '@/components/SysDialog.vue';
import useDialog from '@/hooks/useDialog';
import { FormInstance, ElMessage } from 'element-plus';
import { addAdminUserApi, deleteAdminApi, editAdminApi, getListApi } from '@/api/user/index';
import { User } from '@/api/user/UserModel';
import { Title } from '@/type/BaseEnum';
import useWarnConfirm from '@/hooks/useWarnConfirm';

const printScope = (scope: any) => {
    console.log(scope); // 打印 scope 对象
};

const onInput = (value: string) => {   
    console.log("searchParam.nickName", value);
}

const { global } = useWarnConfirm();

const searchParam = reactive({
    nickName: '',
    pageSize: 10,
    currentPage: 1,
    total: 0
})

const tableList = ref([])
const tableHeight = ref(0)
// const dialog = reactive({
//     title: '标题',
//     visible: false,

// })

// const parentClose = () => {
//     console.log('父组件调用关闭')
//     dialog.visible = false;
// }

// const parentConfirm = () => {
//     console.log('父组件调用确定')
//     dialog.visible = false;
// }

const { dialog, parentClose, parentConfirm } = useDialog();

// 标记当前是新增表单还是编辑表单
const tags = ref('')

const addBtn = () => {
    addModel.nickName = '';
    addModel.sex = '1';
    addModel.phone = '';
    addModel.username = '';
    addModel.password = '';
    addModel.status = '0';

    tags.value = '0' // 0表示新增，1表示编辑
    dialog.title = Title.ADD
    dialog.visible = true
    dialog.height = 300
}


const addModel = reactive({
    nickName: '',
    sex: '0',
    phone: '',
    username: '',
    password: '',
    status: '0',
})

//表单验证规则
// 1.el-form-item加prop属性
// 2.编写表单验证规则 rules
// 3.表单要绑定 :rules="rules"
const rules = reactive({
    username: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
    password: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
    nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
    sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
});
// const rules = reactive<FormRules>({
//     username: [
//         { required: true, message: 'Please input Activity name', trigger: 'blur' },
//         { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
//     ]
// })

const addRef = ref<FormInstance>();

const onConfirm = () => {
    addRef.value?.validate(async (valid) => {
        if (valid) {
            // 提交表单
            let res = null;
            if (tags.value == '0') {
                // 新增
                res = await addAdminUserApi(addModel);
            } else {
                // 编辑
                res = await editAdminApi(addModel);
            }
            if (res && res.code == 200) {
                ElMessage.success(res.msg)
                parentConfirm();
                getList();
            } else {
                ElMessage.error(res.msg)
            }
        }
    })
}

// 查询管理员
const getList = async () => {
    let res = await getListApi(searchParam)
    if (res && res.code == 200) {
        console.log(res)
        tableList.value = res.data.records;
        searchParam.total = res.data.total;
    }
}

onMounted(() => {
    tableHeight.value = window.innerHeight - 200;
    getList()
})

const editBtn = (row: User) => {
    console.log(`editBtn`, row)
    tags.value = '1' // 0表示新增，1表示编辑
    dialog.title = Title.EDIT
    dialog.height = 300
    dialog.visible = true

    //Object.assign(addModel, row)
     
    nextTick(()=>{
        Object.assign(addModel, row)
        console.log('addModel in editBtn',addModel)
    })
}

const instance = getCurrentInstance();

const deleteBtn = async (row: User) => {
    console.log(`deleteBtn`, row)
    console.log(global);
    const confirm = await instance!.appContext.config.globalProperties.$warningConfirm('确定删除该数据吗?')
    // const confirm = await global.$warningConfirm('确定删除该数据吗?')
    if (confirm) {
        let res = await deleteAdminApi(row.userId!)
        if (res && res.code == 200) {
            ElMessage.success(res.msg)
            getList()
        }
    }
}

const sizeChange = (size: number) => {
    console.log(`size`, size)
    searchParam.pageSize = size
    getList()
}

const currentChange = (page: number) => {
    console.log(`page`, page)
    searchParam.currentPage = page
    getList()
}

const searchBtn = () => {
    // 问：为什么没有像searchParam.currentPage = page那样设置searchParam.nickName
    console.log(`search.nickName`, searchParam.nickName)
    getList()
}

const resetBtn = () => {
    searchParam.nickName = ''
    getList()
}
</script>

<style scoped></style>